package cn.bjit.service.impl;

import cn.bjit.config.OSSconfig;
import cn.bjit.service.FileService;
import cn.bjit.util.CommonUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSconfig  ossConfig;

    @Override
    public String uploadUserHeadImg(MultipartFile file) {
         //目标：上传的文件假如是  a.jpg ->user/2022/6/4/12121212121212121212.jpg
         // 1，获取上传的文件
        String originalFilename = file.getOriginalFilename();
        // 2,获取相关配置
        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //3,创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //4，把图片处理成user/2022/6/4/12121212121212121212.jpg样子
        //4-1,去bucket里面新建一个user文件夹
        //4-2,获取当前时间
//        >>原始方式
//        Date d=new Date();
//        SimpleDateFormat  sdf=new SimpleDateFormat("yyyy-MM-dd");
//        String format = sdf.format(d);
          //>>现在的方式
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String  folder= dtf.format(ldt); //获取到的是：2022/06/04
        String fileName= CommonUtil.generateUUID(); //32位的随机数
        //>>4-3,获取上传的图片的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //>>4-4 拼接连接
        String newFileName="user1/"+folder+"/"+fileName+extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            if(result!=null){
                //https://pass-user-service-img.oss-cn-beijing.aliyuncs.com/user/2022/06/03/7b3546fc541e40928347939feaee54b8.png
                String imgUrl = "https://"+bucketName+"."+endpoint+"/"+newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("头像上传失败{}",e);
        }
        return null;
    }
}
